package src.DAO;

import src.jdbc.PostgreSQL;
import src.Entities.Usuario;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
/**
 *
 * @author Rodrigo
 */
public class UsuarioDAO {

    public String deleteUsuario(int usuarioID){
        try {
            String sql = "DELETE FROM usuario WHERE usuario_id = ?;";
            PreparedStatement delete = PostgreSQL.getConnection().prepareStatement(sql);
            delete.setInt(1, usuarioID);
            return String.valueOf(delete.execute());
        } catch (Exception e) {
            return e.toString();
        }
    }

    public String insertUsuario(Usuario user) {
        try {
            String sql = "INSERT " +
                    "       INTO usuario(usuario_id, persona_id, pass, mail, es_admin)" +
                    "     VALUES (NEXTVAL('usuario_seq'), ?,?,?,?)";
            PreparedStatement insert = PostgreSQL.getConnection().prepareStatement(sql);
            insert.setInt(1, user.getPersonaId());
            insert.setString(2, user.getpass());
            insert.setString(3, user.getmail());
            insert.setString(4, String.valueOf(user.getEsAdmin()));
            return String.valueOf(insert.execute());
        } catch (Exception e) {
            return e.toString();
        }
    }

    public ArrayList selectUsuario(String sql) {
        ArrayList results = new ArrayList();
        try {
            Connection con = PostgreSQL.getConnection();
            Statement select = con.createStatement();
            ResultSet query = select.executeQuery(sql);
            while (query.next()) {
                Usuario user = new Usuario(query.getInt("usuario_id"),
                        query.getInt("persona_id"), query.getString("pass"),
                        query.getString("mail"),query.getString("es_admin").charAt(0));
                results.add(user);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return results;
    }

    public String updateUsuario(Usuario user) {
        try {
            String sql = "UPDATE usuario" +
                    "        SET persona_id = ?, pass = ?, mail = ?, es_admin = ?" +
                    "      WHERE usuario_id = ?";
            PreparedStatement update = PostgreSQL.getConnection().prepareStatement(sql);
            update.setInt(1, user.getPersonaId());
            update.setString(2, user.getpass());
            update.setString(3, user.getmail());
            update.setString(4, String.valueOf(user.getEsAdmin()));
            update.setInt(5, user.getUserId());
            return String.valueOf(update.execute());
        } catch (Exception e) {
            return e.toString();
        }
    }
}
